using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

public class Destructiable : MonoBehaviour
{
    public int maxHp = 100;//最大生命值
    private int currentHp; //当前生命值
    
    public List<Sprite> injuredSpriteList = new List<Sprite>();
    
    private SpriteRenderer spriteRenderer;//图片渲染器
    
    private GameObject boomPrefab;//爆炸效果预制体
    
    private void Start()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        currentHp = maxHp;
        //使用Addressables加载资源
        Addressables.LoadAssetAsync<GameObject>("Boom1").Completed += operation=>
        {
            boomPrefab = operation.Result;
        };
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        int damage = (int)collision.relativeVelocity.magnitude * 8;
        TakeDamage(damage);
    }

    public void TakeDamage(int damage)
    {
        //每次碰撞就让它血量减少，根据碰撞强度
        currentHp -= damage;
        
        if (currentHp <= 0)
        {
            Die();
            return;
        }
        
        Sprite beforeSprite = spriteRenderer.sprite;
        int index = (int)((maxHp - currentHp) / (maxHp / (injuredSpriteList.Count + 1.0f))) - 1;
        if (index >= 0)
        {
            spriteRenderer.sprite = injuredSpriteList[index];
        }
        //木头图片改变就播放音效
        if(beforeSprite != spriteRenderer.sprite)
        {
            PlayAudioCollision();
        }
    }

    protected virtual void PlayAudioCollision()
    {
        AudioManager.Instance.PlayWoodCollision(transform.position);//播放木头碰撞音效
    }
    
    protected virtual void PlayAudioDestroyed()
    {
        AudioManager.Instance.PlayWoodDestroyed(transform.position);//播放猪死亡音效
    }
    
    public virtual void Die()
    {
        //死亡前播放爆炸动画
        PlayAudioDestroyed();
        Instantiate(boomPrefab, transform.position, Quaternion.identity);
        Destroy(gameObject);
    }
}
